package com.lagou.handler;

import com.lagou.protocol.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import net.sf.cglib.reflect.FastClass;
import net.sf.cglib.reflect.FastMethod;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 自定义的业务处理器
 */
@Component
public class UserServiceHandler extends ChannelOutboundHandlerAdapter implements ApplicationContextAware {
    private static ApplicationContext applicationContext2;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("初始化上下文。。。。。");
        UserServiceHandler.applicationContext2=applicationContext;
    }
    //当服务端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object rpcRequest) throws Exception {
        System.out.println("服务端provider读取数据。。。");
        RpcRequest rpcReq=(RpcRequest)rpcRequest;
        //获取需要调用的方法名,约定requestID为调用的接口名，
        String className=rpcReq.getClassName();
        System.out.println("className"+className);
        String methodName=rpcReq.getMethodName();
        System.out.println("methodName"+methodName);
        Class<?>[]clazzs=rpcReq.getParameterTypes();
        Object[]parameters=rpcReq.getParameters();
        try{

            Class<?>handleClass=Class.forName(className);
            System.out.println(handleClass);
            Object serviceBean=applicationContext2.getBean(handleClass);
            Class<?> clazz=serviceBean.getClass();
            //如何获取实现类
            System.out.println("加载的实例："+handleClass);
            //新建实例对象
            FastClass fastClass=FastClass.create(clazz);
            FastMethod method=fastClass.getMethod(methodName,clazzs);

            System.out.println("类实例为："+serviceBean);
            System.out.println("方法为："+method);
            method.invoke(serviceBean,parameters);
            ctx.writeAndFlush("success!");
        }catch (ClassNotFoundException e){
            throw new Exception("加载类失败。。。。");
        }catch (Exception e){
            throw  e;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().read();
        System.out.println("有新的客户端连接建立。。。。。。");
    }


}
